import axios from 'axios'
import {errorMsg, warningMsg} from "@/utils/message";
import {closeLoading, showLoading} from "@/utils/loading";
import {getApiVersion, getHtmlVersion, getToken, removeAllCache} from "@/utils/storage";
import router from "@/router/router";
import {SERVER_BASE_URL} from "@/aconst/const";
import $K from "@/utils/kit";

const $http = axios.create({
    timeout: 100 * 1000,
});

// 请求拦截  设置统一header
$http.interceptors.request.use(config => {
    let url: any = config.url;
    let haveHttp = (url + "").indexOf("http://").toString() != "-1";
    let haveHttps = (url + "").indexOf("https://").toString() != "-1";
    config.headers['Token'] = getToken();
    config.headers['adminHtmlVersion'] = getHtmlVersion();
    config.headers['adminApiVersion'] = getApiVersion();
    showLoading(null);
    if (haveHttp || haveHttps) {
    } else {
        config.url = SERVER_BASE_URL + url;
    }
    ////console.log(config.url);
    return config;
}, error => {
    return Promise.reject(error)
});

$http.interceptors.response.use(response => {
    let data: any = response.data;
    if (1 == 1) {
        closeLoading();
        return data;
    }

    if (response.config.responseType && response.config.responseType == "blob") {
        closeLoading();
        return data;
    }

    if (!data.code) {
        return response;
    }

    if (data.code == "get_config_json") {
        return data;
    }

    // if (!data.code) {
    //     return response;
    // }
    // if (data.code == "get_config_json") {
    //     return data;
    // }
    //
    //
    // data.headers = response.headers;
    //请求成功
    if (data.code.toString() == "200") {
    }
    //请求失败
    else if (data.code.toString() == "500") {
        errorMsg(data.message)
    }
        // 咱也不知道啥原因
    // 就是想让用户重新登录
    else if (data.code.toString() == "555") {
        warningMsg("登录状态已失效，请重新登录");
        removeAllCache();
        router.push({path: "/login"});
        // window.location.reload();
    }
    //请求失败
    else if (data.code.toString() == "400") {
        errorMsg(data.message)
    }
    //权限不足
    else if (data.code.toString() == "402") {
        errorMsg(data.message);
        // router.push({path: "/402"});
    }
    //管理端登录失效
    else if (data.code.toString() == "401") {
        errorMsg("登录已失效，请重新登录.");
        removeAllCache();
         $K.to("/login");
    }
    //微信端登录失效
    else if (data.code.toString() == "4011") {
        errorMsg("登录已失效，请重新登录.");
        removeAllCache();
         $K.to("/wx/login");
    }
    //延迟关闭动画
    setTimeout(() => {
        closeLoading();
    }, 100);

    return data;
}, error => {
    ////console.log(error);
    closeLoading();
    if (error.toString().indexOf("404")! - 1) {
        errorMsg("访问资源不存在");
        return;
    }
    errorMsg("操作失败：服务器暂未开启.");
});

export default $http

